package com.boarsoft.boar.common.auth;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.auth.TxtPwdAuth;
import com.boarsoft.boar.common.Logon;
import com.boarsoft.boar.context.ActionContext;
import com.boarsoft.boar.sys.SysPowerBiz;
import com.boarsoft.boar.sys.SysUserBiz;
import com.boarsoft.boar.sys.entity.SysFunc;
import com.boarsoft.boar.sys.entity.SysUser;
import com.boarsoft.cache.Cache;
import com.boarsoft.common.util.BeanUtil;

//@Component("txtPwdAuth")
public class BasicTxtPwdAuthImpl implements TxtPwdAuth {
	private static Logger log = LoggerFactory.getLogger(BasicTxtPwdAuthImpl.class);

	@Autowired
	protected SysUserBiz sysUserBiz;
	@Autowired
	protected SysPowerBiz sysPowerBiz;

	@Override
	public ReplyInfo<Object> authorize(String code, String password) throws Exception {
		// 本地登录，返回UID
		ReplyInfo<Object> ri = sysUserBiz.login(code, password);
		if (!ri.isSuccess()) {
			return ri;
		}
		// 生成token
		SysUser uo = (SysUser) ri.getData();
		sysUserBiz.saveToken(uo, 0);
		String token = uo.getToken();
		// 生成Logon对象，并放入缓存
		Logon lg = new Logon();
		lg.setId(uo.getId());
		lg.setCode(code);
		lg.setEmail(uo.getEmail());
		lg.setName(uo.getName());
		lg.setToken(token);
		lg.setCorpId(uo.getCorpId());
		lg.setDeptId(uo.getDeptId());
		// 查询用户拥有的所有权限
		List<SysFunc> funcs = sysPowerBiz.getMyFuncs(lg.getId(), null);
		for (SysFunc f : funcs) {
			f.setRoles(null);
			SysFunc a = BeanUtil.transfer(f, SysFunc.class);
			lg.getFuncs().add(a);
		}
		ri.setData(lg); // 改为返回logon
		// 如果有配置缓存就放入缓存，否则到数据库读取
		Cache cache = ActionContext.getCache();
		if (cache == null) {
			return ri;
		}
		log.info("Put token {}/{}/{} to cache", token, lg.getCode(), lg.getEmail());
		cache.put("token", token, lg);
		return ri;
	}
}
